Skip to main content

Random Choice

np.random.choice(arr, size, replace=True, p=[p_0, p_1, ...])

Generates a random sample from a given array or list.

Input:
arr: array, list, or integer
If array or list, np.random.choice will sample from those elements. If integer (e.g. 5), np.random.choice will sample from np.arange(5) (aka array([0, 1, 2, 3, 4])).
size : integer, default 1
Number of random samples to draw.
replace : boolean, default True
If True, element can be selected multiple times. If False, each element can only be selected once.
p : array or list, default uniform distribution
Probabilities corresponding with each element in arr.
Returns:
Generated random samples.
Return Type:
Integer or Array
Note:
  • If replace = False, size must be smaller than the length of the array or list. Otherwise, the function will raise a ValueError: Cannot take a larger sample than population when 'replace=False'.

example_array = np.array([1, 2, 3, 4, 5])
example_array

array([1, 2, 3, 4, 5])

np.random.choice(example_array)

1

np.random.choice(example_array, 3, replace=True)

array([5, 2, 3])

np.random.choice(example_array, 3, replace=True, p=[0.05, 0.05, 0.05, 0.05, 0.8])

array([4, 5, 5])

np.random.choice(example_array, 3, replace=True, p=[0, 0, 0, 0, 1])

array([5, 5, 5])

np.random.choice([1, 2], 3, replace=True, p=[0.8, 0.2])

array([2, 1, 2])

np.random.choice([1, 2], 3, replace=False, p=[0.8, 0.2])

ValueError: Cannot take a larger sample than population when 'replace=False'